package com.gjy.concurrency.cf;

import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-22 13:34:46
 */
public class ComFuture1 {

    @Test
    public void test4() {
        CompletableFuture.supplyAsync(() -> "Hello World")
                .thenApplyAsync(s -> s.split(""));
    }

    @Test
    public void test3() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> combine = CompletableFuture.supplyAsync(() -> 2)
                .thenCombine(CompletableFuture.supplyAsync(() -> 2),
                        (l, r) -> l * r);
        System.out.println(combine.get());
    }

    @Test
    public void test2() {
        ArrayList<String> list = Lists.newArrayList();
        for (int i = 0; i < 100; i++) {
            list.add(i + "H");
        }
//        Lists.newArrayList("Hel", "Add", "Update", "Select")
        list.stream()
                .map(s -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return s.split("");
                })
                .collect(Collectors.toList())
                .forEach(array -> System.out.println(Arrays.toString(array)));
    }

    @Test
    public void test1() {
        ArrayList<String> list = Lists.newArrayList();
        for (int i = 0; i < 100000; i++) {
            list.add(i + "H");
        }
//        Lists.newArrayList("Hel", "Add", "Update", "Select")
        List<CompletableFuture<String[]>> collect = list.stream()
                .map(s -> CompletableFuture.supplyAsync(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return s.split("");
                }, Executors.newCachedThreadPool())).collect(Collectors.toList());

        collect.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList())
                .forEach(array -> System.out.println(Arrays.toString(array)));
    }
}
